import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '计数器',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blueAccent),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '计数器'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool _enabled = true;
  double _sliderValue = 0;
  int _step = 1;

  final int _min = 0;
  final int _max = 100;

  void _incrementCounter() {
    if (_enabled) {
      setState(() {
        _counter = (_counter + _step).clamp(_min, _max);
        _sliderValue = _counter.toDouble();
      });
    }
  }

  void _resetCounter() {
    setState(() {
      _counter = 0;
      _sliderValue = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Theme.of(context).colorScheme.primary,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            tooltip: '重置计数器',
            onPressed: _resetCounter,
          ),
        ],
      ),
      body: Stack(
        children: [
          // 渐变背景
          Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFe0eafc), Color(0xFFcfdef3)],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
          ),
          // 动态气泡
          _AnimatedBubbles(),
          // 主内容
          Center(
            child: SingleChildScrollView(
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(32),
                  gradient: LinearGradient(
                    colors: [
                      Colors.white.withOpacity(0.85),
                      Colors.white.withOpacity(0.65),
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.blueAccent.withOpacity(0.08),
                      blurRadius: 32,
                      offset: const Offset(0, 16),
                    ),
                  ],
                  border: Border.all(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                  // 玻璃拟态效果
                  backgroundBlendMode: BlendMode.overlay,
                ),
                margin: const EdgeInsets.all(28),
                padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 36),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ShaderMask(
                      shaderCallback: (Rect bounds) {
                        return const LinearGradient(
                          colors: [Color(0xFF4f8cff), Color(0xFFa6bfff)],
                        ).createShader(bounds);
                      },
                      child: const Text(
                        '当前计数',
                        style: TextStyle(
                          fontSize: 28,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                          shadows: [
                            Shadow(
                              color: Colors.blueAccent,
                              blurRadius: 12,
                              offset: Offset(0, 2),
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 18),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.countertops, color: Colors.blueAccent, size: 38),
                        const SizedBox(width: 12),
                        AnimatedSwitcher(
                          duration: const Duration(milliseconds: 900), // 动画时长调慢
                          transitionBuilder: (child, animation) => ScaleTransition(scale: animation, child: child),
                          child: Text(
                            '$_counter',
                            key: ValueKey<int>(_counter),
                            style: TextStyle(
                              fontSize: 60,
                              fontWeight: FontWeight.bold,
                              color: _enabled ? Colors.blueAccent : Colors.grey,
                              shadows: [
                                Shadow(
                                  color: Colors.blueAccent.withOpacity(0.18),
                                  blurRadius: 10,
                                  offset: const Offset(2, 2),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 32),
                    Row(
                      children: [
                        Icon(Icons.tune, color: Colors.green),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('用滑块设置计数器（$_min~$_max）',
                                  style: TextStyle(color: Colors.grey[700])),
                              Slider(
                                value: _sliderValue,
                                min: _min.toDouble(),
                                max: _max.toDouble(),
                                divisions: _max - _min,
                                label: _sliderValue.round().toString(),
                                onChanged: _enabled
                                    ? (value) {
                                        setState(() {
                                          _sliderValue = value;
                                          _counter = value.round();
                                        });
                                      }
                                    : null,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 22),
                    Row(
                      children: [
                        Icon(Icons.settings, color: Colors.orange),
                        const SizedBox(width: 8),
                        const Text('选择步长:'),
                        const SizedBox(width: 8),
                        DropdownButton<int>(
                          value: _step,
                          borderRadius: BorderRadius.circular(16),
                          style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.blueAccent),
                          items: [1, 2, 5, 10]
                              .map((e) => DropdownMenuItem(
                                    value: e,
                                    child: Text('$e'),
                                  ))
                              .toList(),
                          onChanged: _enabled
                              ? (value) {
                                  setState(() {
                                    _step = value!;
                                  });
                                }
                              : null,
                        ),
                        const SizedBox(width: 8),
                        Text('当前步长: $_step', style: TextStyle(color: Colors.grey[700])),
                      ],
                    ),
                    const SizedBox(height: 22),
                    Row(
                      children: [
                        Icon(Icons.lock_open, color: Colors.purple),
                        const SizedBox(width: 8),
                        const Text('计数器可用:'),
                        Switch(
                          value: _enabled,
                          activeColor: Colors.blueAccent,
                          onChanged: (value) {
                            setState(() {
                              _enabled = value;
                            });
                          },
                        ),
                        _enabled
                            ? const Text('已启用', style: TextStyle(color: Colors.green))
                            : const Text('已禁用', style: TextStyle(color: Colors.red)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _enabled ? _incrementCounter : null,
        label: const Text('增加'),
        icon: const Icon(Icons.add),
      ),
    );
  }
}

// 在文件末尾添加如下动画气泡组件
class _AnimatedBubbles extends StatefulWidget {
  @override
  State<_AnimatedBubbles> createState() => _AnimatedBubblesState();
}

class _AnimatedBubblesState extends State<_AnimatedBubbles> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 12),
      vsync: this,
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Color _bubbleColor(double t, List<Color> colors) {
    int idx = (t * (colors.length - 1)).floor();
    double localT = (t * (colors.length - 1)) % 1;
    return Color.lerp(colors[idx], colors[(idx + 1) % colors.length], localT)!;
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final List<List<Color>> colorSets = [
      [Colors.blueAccent.withOpacity(0.13), Colors.lightBlue.withOpacity(0.10)],
      [Colors.purpleAccent.withOpacity(0.12), Colors.deepPurple.withOpacity(0.10)],
      [Colors.pinkAccent.withOpacity(0.10), Colors.cyanAccent.withOpacity(0.13), Colors.amber.withOpacity(0.10)],
      [Colors.greenAccent.withOpacity(0.10), Colors.tealAccent.withOpacity(0.13)],
      [Colors.orangeAccent.withOpacity(0.10), Colors.deepOrange.withOpacity(0.13)],
      [Colors.redAccent.withOpacity(0.10), Colors.pink.withOpacity(0.13)],
      [Colors.indigo.withOpacity(0.10), Colors.blueGrey.withOpacity(0.13)],
      [Colors.yellow.withOpacity(0.10), Colors.amberAccent.withOpacity(0.13)],
    ];

    return SizedBox.expand(
      child: AnimatedBuilder(
        animation: _controller,
        builder: (context, child) {
          final t = _controller.value;
          List<Widget> bubbles = [];
          for (int i = 0; i < 8; i++) {
            // 每个气泡的动画参数略有不同
            final phase = (t + i * 0.12) % 1.0;
            final x = 40 + (size.width - 80) * (0.1 + 0.8 * ((phase + i * 0.13) % 1.0));
            final y = 60 + (size.height - 160) * (0.1 + 0.8 * ((1 - phase + i * 0.07) % 1.0));
            final bubbleSize = 40 + 40 * (0.5 + 0.5 * (1 - (2 * phase - 1).abs()));
            final color = _bubbleColor(phase, colorSets[i % colorSets.length]);
            bubbles.add(Positioned(
              left: x,
              top: y,
              child: Container(
                width: bubbleSize,
                height: bubbleSize,
                decoration: BoxDecoration(
                  color: color,
                  shape: BoxShape.circle,
                ),
              ),
            ));
          }
          return Stack(children: bubbles);
        },
      ),
    );
  }
}
